const app = getApp();
const utils = require('../../utils/utils.js');
Page({
    data: {
        priceMeal: [],
        leaseTime: 0,
        sn: "",
        isClick: true,
        amount: 0,
        order_id: null,
        checkNum: 0,
        timer: "",
        storeName: "",
        is_show: 0,
        need_tel: 0
    },
    onLoad: function (options) {
        wx.showLoading({
            title: 'loading...',
            mask: true
        });
        let json = JSON.parse(options.data);
        this.setData({
            info: json,
            priceMeal: json.priceMeal,
            leaseTime: json.leaseTime,
            sn: json.sn,
            amount: json.leaseMoney,
            storeName: json.storeName,
            is_show: json.is_show,
            need_tel: json.need_tel
        });
        wx.hideLoading();
        let openid = app.globalData.openID;
        if (openid != 'miand') {
            // 获取用户信息
            this.userIsAuth();
        } else {
            wx.showModal({
                title: '温馨提示',
                content: 'Hi~请确认登录，登录即可享受充电服务',
                success: function (sm) {
                    if (sm.confirm) {
                        // 未授权，跳转到授权页面
                        wx.navigateTo({
                            url: '../authorization/authorization?scene=3'
                        });
                    } else if (sm.cancel) {
                        wx.showToast({
                            title: "您点击了取消",
                            icon: 'none',
                            duration: 2000
                        });
                    }
                }
            })
        }
    },
    onHide: function () {
        let e = this;
        clearInterval(e.data.timer);
    },
    onUnload: function () {
        let e = this;
        clearInterval(e.data.timer);
    },
    // ===================== 判断用户是否授权 =============================
    userIsAuth() {
        let that = this;
        utils.httpRequest('/checkAuth', {}, function (res) {
            if (res.code == 1) {
                if (res.data.is_auth == 1) { //已授权
                    that.getUserInfo();
                } else {
                    // 未获取到用户昵称信息，需要让用户再次授权
                    wx.navigateTo({
                        url: '../authorization/authorization?scene=3'
                    });
                }
            }
        })
    },
    // =============== 获取用户信息 ====================
    getUserInfo() {
        let that = this;
        utils.httpRequest('/getInfo', {}, function (res) {
            if (res.code == 1) {
                that.setData({
                    userInfo: res.data
                })
            }
        })
    },
    // ==================== 点击单选框 ====================================
    radioChange(e) {
        let items = this.data.priceMeal;
        let time = e.detail.value;
        let amount = 0;
        for (let i = 0, lenI = items.length; i < lenI; ++i) {
            if (items[i].time != time) {
                items[i].checked = false;
            } else {
                items[i].checked = true;
                amount = items[i].amount
            }
        }
        this.setData({
            priceMeal: items,
            leaseTime: time,
            amount: amount
        });
    },
    // ==================== 选择套餐时间 ====================================
    choseTime(e) {
        let that = this;
        let time = e.currentTarget.dataset.time;
        let items = this.data.priceMeal;
        let amount = 0;
        for (let i = 0, lenI = items.length; i < lenI; ++i) {
            if (items[i].time != time) {
                items[i].checked = false;
            } else {
                items[i].checked = true;
                amount = items[i].amount
            }
        }
        this.setData({
            priceMeal: items,
            leaseTime: time,
            amount: amount
        });
    },
    // ============================ 租借充电线 =============================
    LineBorrow() {
        let openid = app.globalData.openID;
        if (openid == 'miand') {
            wx.showModal({
                title: '温馨提示',
                content: 'Hi~请确认登录，登录即可享受充电服务',
                success: function (sm) {
                    if (sm.confirm) {
                        // 未授权，跳转到授权页面
                        wx.navigateTo({
                            url: '../authorization/authorization?scene=3'
                        });
                    } else if (sm.cancel) {
                        wx.showToast({
                            title: "您点击了取消",
                            icon: 'none',
                            duration: 2000
                        });
                    }
                }
            })
            return;
        }
        let that = this;
        if (that.data.isClick) {
            let order_id = that.data.order_id;
            let amount = that.data.amount;
            wx.showLoading({
                title: '请稍后...',
                mask: true
            })
            that.setData({
                isClick: false
            })
            if (that.data.leaseTime > 0) {
                utils.httpRequest('/LineBorrow', {
                    sn: that.data.sn,
                    time: that.data.leaseTime,
                    amount: amount,
                    order_id: order_id
                }, function (res) {
                    switch (res.code) {
                        case 1:
                            //租借
                            // that.setData({
                            //     isClick: true
                            // })
                            wx.hideLoading();
                            // 跳转到线密码界面
                            wx.navigateTo({
                                url: '../linePassword/linePassword?data=' + JSON.stringify(res.data)
                            })
                            break;
                        case 3:
                            // 未支付，发起支付
                            wx.hideLoading();
                            wx.showLoading({
                                title: '请稍后...',
                                mask: true
                            })
                            utils.wxPayPayment(res.data.amount, 3, res.data.sn, res.data.time, function (order_id) {
                                wx.hideLoading();
                                if (order_id != null) {
                                    that.checkOrderStatus(order_id);
                                } else {
                                    that.setData({
                                        isClick: true
                                    });
                                }
                            }, function () {
                                that.setData({
                                    isClick: true
                                })
                                wx.hideLoading();
                            });
                            break;
                        default:
                            that.setData({
                                isClick: true
                            });
                            wx.hideLoading();
                            break;
                    }
                }, function () {
                    that.setData({
                        isClick: true
                    });
                    wx.hideLoading();
                })
            } else {
                that.setData({
                    isClick: true
                });
                wx.showToast({
                    title: "请选择对应的价格套餐",
                    icon: 'none',
                    duration: 2000
                });
            }
        }
    },
    // ====================== 校验用户是否支付成功  ===========================================
    checkOrderStatus(order_id) {
        let that = this;
        let check = that.data.checkNum;
        check++;
        that.setData({
            checkNum: check
        })
        if (that.data.checkNum < 35) {
            utils.httpRequest('/checkOrderStatus', {
                order_id: order_id,
                freeDeposit: 0
            }, function (res) {
                if (res.data.status == 1) {
                    wx.hideLoading();
                    that.setData({
                        order_id: res.data.order_id,
                        isClick: true
                    });
                    clearInterval(that.data.timer);
                    that.LineBorrow();
                } else {
                    var timerTem = setTimeout(() => {
                        that.checkOrderStatus(order_id);
                    }, 1500);
                    that.setData({
                        timer: timerTem
                    });
                }
            }, function () {
                wx.hideLoading();
            })
        } else {
            wx.hideLoading();
            wx.showToast({
                title: "订单异常,请联系客服",
                icon: 'none',
                duration: 2000
            });
        }
    },
    // ================== 授权手机号 ===================
    getPhoneNumber(e) {
        var errMsg = e.detail.errMsg;
        var iv = e.detail.iv;
        var encryptedData = e.detail.encryptedData;
        let that = this;
        if (errMsg == "getPhoneNumber:fail:user deny") {
            // 用户拒绝
            let refuseShow = that.data.info.refuse_show;
            let refuseAfterToBorrow = that.data.info.refuse_after_borrow;
            // console.log("refuseShow --> " + refuseShow);
            if (refuseShow == 1) {
                wx.showModal({
                    title: '温馨提示',
                    content: that.data.refuse_msg,
                    showCancel: false,
                    confirmText: '确认',
                    success: function (res) {
                        if (res.confirm) {
                            if (refuseAfterToBorrow == 1) {
                                that.setData({
                                    need_tel: 0
                                });
                            }
                        }
                    }
                })
            } else {
                if (refuseAfterToBorrow == 1) {
                    that.setData({
                        need_tel: 0
                    });
                }
            }
        } else {
            wx.login({
                success(res) {
                    if (res.code) {
                        utils.httpRequest('/login', {
                            code: res.code
                        }, function (res) {
                            // 用户允许授权
                            utils.httpRequest('/getPhoneNumber', {
                                "iv": iv,
                                "encryptedData": encryptedData
                            }, function (res) {
                                if (res.code == 1) {
                                    wx.showToast({
                                        title: "授权成功",
                                        icon: 'none',
                                        duration: 2000
                                    });
                                } else {
                                    that.setData({
                                        need_tel: 1
                                    });
                                }
                            });
                        })
                    }
                }
            });
            // 不管是否授权成功，只要用户点击了授权，则设置成功
            that.setData({
                need_tel: 0
            });
        }
    }
})